package com.lanou.beautifulwardrobe.dbHelper;

import android.util.Log;

import com.lanou.beautifulwardrobe.application.BaseApplication;
import com.lanou.beautifulwardrobe.entity.greendao.DaoSession;
import com.lanou.beautifulwardrobe.entity.greendao.ProductEntity;
import com.lanou.beautifulwardrobe.entity.greendao.ProductEntityDao;

import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 15/11/9.
 */
public class ProductsDBHelper {
    private static ProductsDBHelper helper;
    private static DaoSession daoSession;

    private ProductsDBHelper() {

    }

    public static ProductsDBHelper getInstance() {
        if (helper == null) {
            helper = new ProductsDBHelper();
            daoSession = BaseApplication.getDaoSession();
        }
        return helper;
    }

    /**
     * 插入一个用户对象
     *
     * @param usersEntity
     */
    public void addUser(ProductEntity productEntity) {
        daoSession.getProductEntityDao().insertInTx(productEntity);
        Log.i("lanou", "增加一用户***");
    }

    public boolean isSaved(String brandName) {
        QueryBuilder<ProductEntity> db = daoSession.getProductEntityDao().queryBuilder();
        db.where(ProductEntityDao.Properties.BrandName.eq(brandName));
        db.buildCount().count();
        return db.buildCount().count() > 0 ? true : false;
    }

    public List<ProductEntity> queryAll() {
        return daoSession.getProductEntityDao().loadAll();
    }

    public void deleteBy(ProductEntity productEntity) {

        if (isSaved(productEntity.getBrandName())) {
            QueryBuilder<ProductEntity> db = daoSession.getProductEntityDao().queryBuilder();
            db.where(ProductEntityDao.Properties.BrandName.eq(productEntity.getBrandName()));
            daoSession.getProductEntityDao().delete(productEntity);
        }
    }

}
